<template>
	<view class="voice-content" @click="handlePlay">
		<view class="play-voice">
			<image src="/static/images/voice_white.png" mode="aspectFill" />
			{{ voice.duration }}"
		</view>
		<view>
			<text :class="playing ? 'cuIcon-stop' : 'cuIcon-playfill'"></text>
		</view>
	
	</view>
</template>

<script setup lang="ts">
import { onMounted, ref, Ref } from 'vue';
// #ifdef H5
import dd from "gdt-jsapi"
// #endif

const props = defineProps({
	voice: {
		type: Object,
		default: {}
	}
})

let voiceData: any = {}
let autoStopTimeout = null

const playing: Ref<boolean> = ref(false)
const recordingFinished: Ref<boolean> = ref(false)

const downloadVoice = (): Promise<void> => {
	return new Promise((resolve, reject):void => {
		dd.downloadAudio({
		  mediaId: props.voice.media_id
		}).then((res:any) => {
			voiceData.localAudioId = res.localAudioId
			recordingFinished.value = true
			resolve()
		}).catch((err:any) => {
			console.log(err)
			uni.showToast({
				icon: "none",
				title: "录音下载失败" + JSON.stringify(err)
			})
			reject()
		})
	})
}
const handlePlay = async () => {
	if (!recordingFinished.value) {
		uni.showLoading({
			title: "音频载入中"
		})
		await downloadVoice()
		uni.hideLoading()
	}
	if (playing.value) {
		dd.stopAudio({
			localAudioId : voiceData.localAudioId,
		}).then(() => {
			playing.value = false
			clearTimeout(autoStopTimeout)
		}).catch((err) => {
			uni.showToast({
				icon: "none",
				title: "录音停止失败" + JSON.stringify(err)
			})
		})
	} else {
		
		dd.playAudio({
			localAudioId : voiceData.localAudioId,
		}).then(() => {
			
			playing.value = true
			autoStopTimeout = setTimeout(() => {
				playing.value = false
			}, voiceData.duration * 1000)
		}).catch(err => {
			uni.showToast({
				icon: "none",
				title: "录音播放失败" + JSON.stringify(err)
			})
		})
	}
}

onMounted(() => {
	console.log("res", props.voice.media_id)
	voiceData = {
		media_id: props.voice.media_id
	}
})
</script>

<style lang="stylus" scoped>
.voice-content
	margin-top: 10rpx
	border-radius: 6rpx
	display: flex
	align-items: center
	background-color: #5789e4
	box-sizing: border-box
	padding: 10rpx 20rpx
	justify-content: space-between
	.play-voice
		height: 66rpx
		width: 430rpx
		border-radius: 12rpx
		display: flex
		align-items: center
		font-weight: bold
		color #fff
		image
			width: 44rpx
			height: 44rpx
			padding: 11rpx
			margin-right: 10rpx
.voice-content:active
	background-color: #447de4
</style>